package com.itxiuyixiu.volunteer.service;

import com.itxiuyixiu.tools.sender.SimpleEmailService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author 黄磊
 * @date 2020/5/7
 */
@Service
public class VerificationService {
    private final String prefix = "email:";
    private final SimpleEmailService emailService;
    private final StringRedisTemplate stringRedisTemplate;
    private final ValueOperations<String, String> redisOperations;
    private final Random random = new Random();
    @Value("${spring.profiles.active:dev}")
    private String profilesActive;

    public VerificationService(SimpleEmailService emailService, StringRedisTemplate stringRedisTemplate) {
        this.emailService = emailService;
        this.stringRedisTemplate = stringRedisTemplate;
        this.redisOperations = stringRedisTemplate.opsForValue();
    }

    public boolean sendVerification(@NonNull String email) {
        String verification = getVerification();
        if (!emailService.sendSimpleMail(email, "志愿者之家", "您的验证码是：" + verification + "\n请在15分钟内输入")) {
            return false;
        }
        redisOperations.set(prefix + email, verification, 15, TimeUnit.MINUTES);
        return true;
    }

    public boolean checkVerification(@NonNull String email, @NonNull String verification) {
        String key = prefix + email;
        String s = redisOperations.get(key);
        if (s == null && profilesActive.matches("(dev)|(test)")) {
            if ("123456".equals(verification)) {
                return true;
            }
        }
        if (s != null && s.equals(verification)) {
            // 用过一次的验证码要被删除的
            stringRedisTemplate.delete(key);
            return true;
        }
        return false;
    }

    private String getVerification() {
        return String.format("%06d", random.nextInt(1000000));
    }
}
